#ifndef _THREAD_SYNC_H_
#define _THREAD_SYNC_H_

#include "list.h"
#include "stdint.h"

// 信号量
struct semaphore_t
{
  uint8_t     value;   // 信号量的value
  struct list waiters; // 等待次信号量的线程队列
};

struct mutex_t
{
  struct task_struct* holder; // 互斥锁的占有者
  struct semaphore_t
      semaphore; // 互斥锁的semaphore实现，value=1表示只有一个资源，此时信号量就是互斥锁
  uint32_t holder_repeat_nr; // 锁的持有者重复申请的次数
};

/**
 * @brief Initializes a semaphore
 *
 * @param sema Pointer to the semaphore to be initialized
 * @param value Initial value of the semaphore
 */
void sema_init(struct semaphore_t* sema, uint8_t value);

/**
 * @brief Performs the P operation on a semaphore, i.e., takes one resource
 *
 * @param sema Pointer to the semaphore to be operated on
 */
void sema_down(struct semaphore_t* sema);

/**
 * @brief Performs the V operation on a semaphore, i.e., releases one resource.
 *
 * @param sema Pointer to the semaphore to release resources from.
 */
void sema_up(struct semaphore_t* sema);

/**
 * @brief Initializes a mutex.
 *
 * @param mutex Pointer to the mutex to be initialized.
 */
void mutex_init(struct mutex_t* mutex);

/**
 * @brief Tries to acquire a mutex.
 *
 * @param mutex Pointer to the mutex to be acquired.
 */
void mutex_acquire(struct mutex_t* mutex);

/**
 * @brief Tries to release a mutex.
 *
 * @param mutex Pointer to the mutex to be released.
 */
void mutex_release(struct mutex_t* mutex);

#endif
